const path = require('path')
const {
  app,
  Menu,
  Tray,
  clipboard,
  globalShortcut,
  BrowserWindow
} = require('electron')
let tray = null
// 存储剪切项  const声明，只代表指针不变
const clippings = []

let browserWindow = null
// 不同平台切换icon
const getIcon = () => {
  if (process.platform === 'win32') {
    return '/icon.ico'
  }
  return '/icon.png'
}

// 更新菜单
const updateMenu = () => {
  const menu = Menu.buildFromTemplate([
    {
      label: 'Creat New Clipping',
      click() {addClipping()},
      accelerator: 'CommandOrControl + Shift + C'
    },
    {type: 'separator'},
    ...clippings.slice(0, 10).map((clipping, index) => {
      return {
        label: clipping.length > 20 ?
                    clipping.slice(0, 20) + '...' :
                    clipping,
        click() {
          console.log('accelerator clipping', clipping)
          clipboard.writeText(clipping)
        },
        // 这里必须用es6的字符串模板写法，普通的字符串拼接方式不行
        accelerator: `CommandOrControl + ${index}`
      }
    }),
    {type: 'separator'},
    {
      label: 'Quit',
      click() {app.quit()},
      accelerator: 'CommandOrControl + Q'
    }
  ])
  tray.setContextMenu(menu)
}

// 将一个剪切项添加到clippings[]数组中
const addClipping = () => {
  const clipping = clipboard.readText()
  if (clippings.includes(clipping)) return
  clippings.unshift(clipping)
  updateMenu()
  return clipping
}

app.on('ready', () => {
  if (app.dock) {
    app.dock.hide()
  }
  // 启动一个隐藏的浏览器窗口，用于加载HTML页面
  browserWindow = new BrowserWindow({
    show: false,
    webPreferences: {
      nodeIntegration: true
    }
  })
  browserWindow.loadURL(`file://${__dirname}/index.html`)
  // browserWindow.webContents.loadFile('./index.html')
  tray = new Tray(path.join(__dirname, getIcon()))

  if (process.platform === 'win32') {
    tray.on('click', tray.popUpContextMenu)
  }

  // 注册全局快捷键
  const activationShortcut = globalShortcut.register(
    'CommandOrControl + Option + C',
    () => {tray.popUpContextMenu()})
  if (!activationShortcut) {
    console.error('Global activation shortcut failed to register')
  }
  

  const newClippingShortcut = globalShortcut.register(
    'CommandOrControl + Shift + Option + C',
    () => {
      const clipping = addClipping()
      console.log('clipping', clipping)
      if (clipping) {
        browserWindow.webContents.send('show-notification', 'Clippping Added', clipping)
      }
    })
  if (!newClippingShortcut) {
    console.error('Global new clipping shortcut failed to register')
  }
  updateMenu()

  tray.setToolTip('Clipmaster')
})
